<template>
  <Card title="合计字段" :head-style="{ textAlign: 'center', fontWeight: 'bold' }">
    <template #extra>
      <a-button size="small" type="primary" @click="handleCreate">添加字段</a-button>
    </template>
    <div class="w-full flex flex-wrap gap-2">
      <div v-for="(item, index) in dataRef" :key="index" class="flex gap-2 items-center">
        <Select
          :options="filedList"
          v-model:value="item.calcFieldCode"
          style="width: 150px"
          @change="handleChange"
          :getPopupContainer="(trigger) => trigger?.parentNode"
        />
        <Select
          :options="calcFuncList"
          v-model:value="item.calcFunc"
          style="width: 100px"
          @change="handleChange"
          :getPopupContainer="(trigger) => trigger?.parentNode"
        />
        <span class="cursor-pointer" @click="handleDelete(index)">x</span>
      </div>
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, watch, unref, onMounted } from 'vue';
  import { Card, Select } from 'ant-design-vue';
  import { isArray } from '/@/utils/is';
  import { getFormGetFieldsByNumeric } from '/@/api/formDesign/formDesign';
  // import { useRouter } from 'vue-router';
  const emit = defineEmits(['update:modelValue']);
  const props = defineProps({
    modelValue: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    formCode: {
      type: String,
      default: '',
    },
  });
  const dataRef = ref<Recordable[]>([]);
  const filedList = ref<Recordable[]>([]);

  const calcFuncList = [
    {
      value: '0',
      label: '求和',
    },
    {
      value: '1',
      label: '求平均值',
    },
  ];

  const handleCreate = () => {
    dataRef.value.push({
      calcFieldCode: '',
      calcFunc: '0',
    });
    handleChange();
  };

  watch(
    () => props.modelValue,
    (newVal) => {
      dataRef.value = [];
      if (isArray(newVal)) {
        dataRef.value = newVal ?? [];
      }
    },
    {
      immediate: true,
    },
  );

  // const { currentRoute } = useRouter();
  const fetch = async () => {
    // const { query } = currentRoute.value;
    if (!props?.formCode) return;
    const data = await getFormGetFieldsByNumeric({ formCode: props.formCode });
    filedList.value = data;
    if (isArray(filedList.value)) {
      filedList.value.forEach((item) => {
        delete item.options;
        item.label = item.title;
        item.value = item.name;
      });
    } else {
      filedList.value = [];
    }
    filedList.value.unshift({
      value: '',
      label: '无',
    });
  };
  watch(
    () => props.formCode,
    () => {
      fetch();
    },
  );
  onMounted(fetch);

  const handleDelete = (index) => {
    dataRef.value.splice(index, 1);
    handleChange();
  };

  const handleChange = () => {
    console.log('uui', dataRef.value);
    emit('update:modelValue', unref(dataRef));
  };
</script>
